package org.tedu.weibo.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.tedu.weibo.common.result.JsonResult;
import org.tedu.weibo.common.result.StatusCode;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getFieldError().getDefaultMessage();
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.VALIDATE_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException e) {
        String message = e.getMessage();
        message = message.substring(message.indexOf(":") + 1).trim();
        System.out.println("message: " + message);
        log.error(message, e);
        return new JsonResult(StatusCode.VALIDATE_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandlerThrowable(Throwable e) {
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }
}
